package com.mediacloud.app.newsmodule.activity.audio;

import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadata;
import android.media.session.PlaybackState;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableKt;
import androidx.core.widget.NestedScrollView;
import androidx.palette.graphics.Palette;

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.chinamcloud.audioserver.APSLifecycleKit;
import com.chinamcloud.audioserver.MusicEntity;
import com.chinamcloud.report.ReportKit;
import com.eventTrack.CDPTrackReportManager;
import com.eventTrack.TXReportManager;
import com.gyf.immersionbar.ImmersionBar;
import com.hebeimodule.view.ExpandLayout;
import com.jaeger.library.StatusBarUtil;
import com.lzf.easyfloat.interfaces.OnPermissionResult;
import com.lzf.easyfloat.permission.PermissionUtils;
import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.adaptor.BaseAdaptor;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.interfaces.IPermissionsAgree;
import com.mediacloud.app.model.interfaces.PermissionUtil;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.LWebView;
import com.mediacloud.app.newsmodule.activity.StyleSetActivity;
import com.mediacloud.app.newsmodule.adaptor.comment.x.XCommentDialogFragment;
import com.mediacloud.app.newsmodule.utils.AppfacBuyEnableUtils;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.TopicListDataInvoker;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.newsmodule.utils.support.SupportKit;
import com.mediacloud.app.newsmodule.view.AudioBottomPopWinX;
import com.mediacloud.app.newsmodule.view.BaseSpiderView;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.XKey;
import com.tencent.mmkv.MMKV;
import com.utils.ClickUtils;
import com.utils.SystemServiceManager;
import com.utils.UriTool;
import com.utils.read.AudioFloatManager;

import org.greenrobot.eventbus.EventBus;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import xyz.doikki.videoplayer.util.PlayerUtils;

/**
 * 音频点直播 的基类 主要是处理了布局  分享等功能
 *
 * @author x
 */
@SuppressWarnings("ALL")
public abstract class BaseAudioActivityHalfCCTV7 extends StyleSetActivity implements OnClickListener {
    private TextView showMoreDes;
    protected TextView tvAuthor;
    protected TextView tvPlayCount;
    protected TextView tvPublishData;
    protected TextView titleView;
    protected ImageView logoView;
    protected View summaryLayout;//简介view
    protected TextView speedIv;
    protected TextView tvProgress;
    protected TextView tvMax;
    protected SeekBar seekbar;
    protected CheckBox togglePauseBtn;
    protected ImageView iv_more;
    protected TextView streamLineBtn;
    protected TextView audioDesTitle;
    protected TextView audioDes;
    protected ImageView summaryOpen;
    protected com.mediacloud.app.model.view.WebBrowser webBrowser;
    protected ExpandLayout tvLayout;
    // protected RelativeLayout rl_webBrowser;
    // protected TextView tv_webmore;
    // public int webMaxHeight = 0;
    protected BaseSpiderView spiderView;
    // protected TextView tv_summary;

    protected TextView text_editor;
    protected TextView text_source;

    protected boolean isAutoPlay = true;
    protected String cdnEncrypt;
    protected CatalogItem catalogItem;

    boolean loadedImg;
    protected boolean openLikeBtn;
    protected final int TYPE_NO_NETWORK = 0;// 無網絡
    protected final int TYPE_NOT_WIFI = 1; //不是WIFI
    protected Dialog dialog;
    protected int dialogType = -1;

    protected TopicListDataInvoker topicListDataInvoker;
    protected ReadStatusInvoker readStatusInvoker;
    protected View logoContainer;
    protected View albumLogoTag;
    protected APSLifecycleKit apsKit;
    protected AudioBottomPopWinX<String> audioBottomPopWin;
    protected int audioType = 0; //0 点播 1直播 2 剧集

    protected TextView programView;
    //定时
    protected List<String> timingList;
    protected int timeOffIndex = 0;
    protected String timeOffInfo = null;
    protected TextView timingTv;
    private TimingAdaptor timingAdapter;
    private Timer timer = new Timer();
    private TimerTask timerTask;
    //点播的
    protected View seekBack15;
    protected View seekForward15;
    protected View lastAudio;
    protected View nextAudio;

    protected AudioAlbumProgramAdapter audioAlbumProgramAdapter;
    private TimePickerBottomDialog customTimeOffSelector;

   public static final String AUDIO_TYPE="AUDIO_TYPE";
    public int floatTop = 0;
    ViewGroup componentLinear;

    private int bgColor = -1;
    protected View tabContainer;
    protected TextView soundTv;
    protected TextView textTv;
    protected View soundLine;
    protected View textLine;
    private NestedScrollView scrollView;
    protected View floatContainer;
    private int hideHeight;
    protected boolean isSoundMod = true;
    protected LWebView textWeb;
    protected View textWebContainer;
    long mTyReportPlayTime = 0;
    protected String AudioAlbumArticleId;
    private boolean checkCurrent = false;

    protected TextView text_comment_audio, text_like_audio, text_share_audio, text_collect_audio;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setSupportSwipe(false);
        super.onCreate(savedInstanceState);
        hideHeight = getResources().getDimensionPixelSize(R.dimen.dimen40);
        // getPermission();
        launchTimeLong = System.currentTimeMillis();
        initView();
        audioBottomPopWin = new AudioBottomPopWinX<>(this);
//        SlideBackLayout slidebackLayout = new SlideBackLayout(this, scrollView);
//        slidebackLayout.bind();
        AudioAlbumArticleId = getIntent().getStringExtra("AudioAlbumArticleId");
        getArgs();
        //setLogo();
        audioType = getIntent().getIntExtra(AUDIO_TYPE, 0);
        if (!TextUtils.isEmpty(articleItem.getReal_title())) {
            titleView.setText(articleItem.getReal_title());
        } else {
            titleView.setText(articleItem.getTitle());
        }
        if (audioType != 2) {
            //不是剧集就隐藏剧集标记
            albumLogoTag.setVisibility(View.GONE);
        }
        logoContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        if (articleItem != null) readStatus();
        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        initAPS();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        AppfacBuyEnableUtils.refresh(this, false);
        showPageTransition();
        if (summaryOpen != null)
            summaryOpen.setOnClickListener(v -> {

                if (showMoreDes.isSelected()) {
                    audioDes.setMaxLines(1);
                    summaryOpen.animate().rotationBy(-180).start();
                } else {
                    audioDes.setMaxLines(Integer.MAX_VALUE);
                    summaryOpen.animate().rotationBy(180).start();
                }
                showMoreDes.setSelected(!showMoreDes.isSelected());
            });
        AppfacBuyEnableUtils.refresh(this, true);
        timingList = new ArrayList<>();
        timingAdapter = new TimingAdaptor(this, timingList);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatusBarUtil.setDarkMode(this);
    }

    @Override
    public boolean showTitleBar() {
        return false;
    }

    public long startPos = 0L;
    public long stopTouchPos = 0L;
    SimpleDateFormat format = new SimpleDateFormat("mm:ss");

    private void initAPS() {

        String taskId;
        if (!TextUtils.isEmpty(AudioAlbumArticleId)) {
            taskId = AudioAlbumArticleId;
        } else {
            taskId = "" + articleItem.getId();
        }

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progress = -1;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                this.progress = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                progress = -1;
                startPos = apsKit.getCurrentPosition();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                stopTouchPos = apsKit.getCurrentPosition();

                if (progress > 0) {
                    String speed = speedIv.getText().toString();
                    if ("倍速".equals(speed)) {
                        speed = "1.0X";
                    }
                }
            }
        });

        apsKit = new APSLifecycleKit(this, taskId, seekbar, new APSLifecycleKit.APSCallback() {
            @Override
            public void onServiceConnected(@Nullable ComponentName name, @Nullable IBinder iBinder) {
                super.onServiceConnected(name, iBinder);
                timeOffInfo = apsKit.getTimeOffInfo();
                // if ("播完当前".equals(timeOffInfo) || "播完两集".equals(timeOffInfo)) {
                if ((timeOffInfo != null && timeOffInfo.indexOf("播完当前") >= 0)) {
                    if (!isFinish) {
                        timingTv.setText("定时");
                    }
                }
                if ("播完两集".equals(timeOffInfo)) {
                    if (!isFinish) {
                        timingTv.setText(timeOffInfo);
                    }
                }
                apsKit.setLoop(true);
                if (audioAlbumProgramAdapter != null) {
                    audioAlbumProgramAdapter.notifyDataSetChanged();
                }
                //if (audioType == 2) {
                MusicEntity musicEntity = apsKit.getCurrentMusic();
                if (apsKit != null && musicEntity != null && !TextUtils.isEmpty(musicEntity.getMusicTitle())) {
                    titleView.setText(musicEntity.getMusicTitle());
                }
                refreshMusicData();
                // }
            }

            @Override
            public void onUpdateProgress(@Nullable IMediaPlayer mediaPlayer) {
                super.onUpdateProgress(mediaPlayer);
                if (mediaPlayer != null) {
                    if (seekbar.getProgress() >= seekbar.getMax()) {
                        isCompleted = true;
                        TXReportManager.getInstance().app_jhapp_content_detail_interact("播完音频"
                                , "是"
                                , String.valueOf(seekbar.getMax() - startPosition / 1000)
                                , articleItem);
                    }
                    if (audioType == 1){
                        seekbar.setMax(100);
                        seekbar.setProgress(100);
                    }
                    tvProgress.setText(format.format(new Date(mediaPlayer.getCurrentPosition())));
                    int progress = seekbar.getMax() - seekbar.getProgress();
                    int min = progress / 60;
                    int sec = progress % 60;
                    if (checkCurrent) {
                        if (progress <= 0) {
                            timingTv.setText("定时");
                            apsKit.stop();
                        } else {
                            timingTv.setText((min > 9 ? min : "0" + min) + ":" + (sec > 9 ? sec : "0" + sec));
                            if (seekbar.getProgress() == 0) {
                                timingTv.setText("定时");
                            }
                        }
                    }
                }

                if (audioAlbumProgramAdapter != null) {
                    TextView playingPositionTV = audioAlbumProgramAdapter.getPlayingPositionTV();
                    if (playingPositionTV != null && mediaPlayer != null) {
                        long duration = mediaPlayer.getDuration();
                        int percent = 0;
                        if (duration != 0) {
                            percent = (int) (mediaPlayer.getCurrentPosition() * 100 / duration) + 1;
                        }
                        if (percent >= 100) {
                            percent = 99;
                        }
                        playingPositionTV.setText("已听" + percent + "%");
                    }
                }
//                if (seekBack15 != null && seekForward15 != null) {
//                    boolean canBack = mediaPlayer.getCurrentPosition() > 15000;
//                    if (canBack) {
//                        if (!seekBack15.isEnabled()) {
//                            seekBack15.setEnabled(true);
//                        }
//                    } else {
//                        if (seekBack15.isEnabled()) {
//                            seekBack15.setEnabled(false);
//                        }
//                    }
//                    boolean canForward = mediaPlayer.getCurrentPosition() < mediaPlayer.getDuration() - 15000;
//                    if (canForward) {
//                        if (!seekForward15.isEnabled()) {
//                            seekForward15.setEnabled(true);
//                        }
//                    } else {
//                        if (seekForward15.isEnabled()) {
//                            seekForward15.setEnabled(false);
//                        }
//                    }
//                }

            }

            @Override
            public void onBufferingUpdate(@Nullable IMediaPlayer mediaPlayer, int percent) {
                super.onBufferingUpdate(mediaPlayer, percent);
            }

            @Override
            public void onCompletion(@Nullable IMediaPlayer mediaPlayer) {
                super.onCompletion(mediaPlayer);
            }


            @Override
            public void onMetadataChanged(@Nullable MediaMetadata metadata) {
                super.onMetadataChanged(metadata);
                if (!isFinish) {
                    titleView.setText(metadata.getString(MediaMetadata.METADATA_KEY_TITLE));
                    refreshMusicData();
                }
            }

            @Override
            public void onPlaybackStateChanged(@Nullable PlaybackState state) {
                super.onPlaybackStateChanged(state);
                String speed = speedIv.getText().toString();
                if ("倍速".equals(speed)) {
                    speed = "1.0X";
                }
                switch (state.getState()) {
                    case PlaybackState.STATE_NONE://无任何状态
                        togglePauseBtn.setChecked(false);
                        break;
                    case PlaybackState.STATE_STOPPED:
                    case PlaybackState.STATE_PAUSED:
                        togglePauseBtn.setChecked(false);
                        stopPosition = apsKit.getCurrentPosition();
                        TXReportManager.getInstance().app_jhapp_content_detail_interact("暂停播放音频", isCompleted ? "是" : "否", String.valueOf((stopPosition - startPosition) / 1000), articleItem, 0, null, null, "", "", "", "", PlayerUtils.stringForTime((int) startPosition), "", PlayerUtils.stringForTime((int) stopPosition));
                        break;
                    case PlaybackState.STATE_PLAYING:
                        startPosition = apsKit.getCurrentPosition();
                        mTyReportPlayTime = System.currentTimeMillis();
                        TXReportManager.getInstance().app_jhapp_content_detail_interact("开始播放音频", null, null, articleItem, 0, null, PlayerUtils.stringForTime((int) startPosition));
                        togglePauseBtn.setChecked(true);
                        check();
                        onToggleClick();//切换倍速
                        break;
                    case PlaybackState.STATE_SKIPPING_TO_NEXT://下一首
                        break;
                    case PlaybackState.STATE_SKIPPING_TO_PREVIOUS://上一首
                        break;
                    case PlaybackState.STATE_FAST_FORWARDING://快进
                        break;
                    case PlaybackState.STATE_REWINDING://快退
                        break;
                    case PlaybackState.STATE_BUFFERING:
                        try {
//                            startPosition = apsKit.getCurrentPosition();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }

            @Override
            public void onPrepared(@Nullable IMediaPlayer mediaPlayer) {
                super.onPrepared(mediaPlayer);
                if (audioAlbumProgramAdapter != null) {
                    audioAlbumProgramAdapter.notifyDataSetChanged();
                }

//                if (lastAudio != null && nextAudio != null) {
//
//                    if (apsKit.enableSkippingToNext()) {
//                        if (!nextAudio.isEnabled()) {
//                            nextAudio.setEnabled(true);
//                        }
//                    } else {
//                        if (nextAudio.isEnabled()) {
//                            nextAudio.setEnabled(false);
//                        }
//                    }
//
//                    if (apsKit.enableSkippingToPrevious()) {
//                        if (!lastAudio.isEnabled()) {
//                            lastAudio.setEnabled(true);
//                        }
//                    } else {
//                        if (lastAudio.isEnabled()) {
//                            lastAudio.setEnabled(false);
//                        }
//                    }
//                }

            }

            @Override
            public void onTimeOffCountDown(long millisUntilFinished) {
                super.onTimeOffCountDown(millisUntilFinished);
                if (!isFinish) {
                    timingTv.setText(APSLifecycleKit.turnTime((int) (millisUntilFinished / 1000)));
                }
            }

            @Override
            public void onTimeOffCountDownFinish() {
                super.onTimeOffCountDownFinish();
                if (!isFinish) {
                    apsKit.stop();
                    timingTv.setText("定时");
                    timeOffIndex = 0;
                }
            }
        });
        apsKit.setAutoPlay(audioType == 2 || isAutoPlay);
        if (audioType == 2 || isAutoPlay) {
            //  KillMusicUtils.hideReadNewsWin();
        }
    }

    //刷新获取当前播放音乐的信息
    abstract void refreshMusicData();


    protected boolean needLoadTopBgSkin() {
        return false;
    }

    public ShareWrap shareWrapTopRight;

    @SuppressWarnings("deprecation")
    protected void initView() {

        text_comment_audio = findViewById(R.id.text_comment_audio);
        text_like_audio = findViewById(R.id.text_like_audio);
        text_share_audio = findViewById(R.id.text_share_audio);
        text_collect_audio = findViewById(R.id.text_collect_audio);


        textWebContainer = findViewById(R.id.textWebContainer);
        textWeb = findViewById(R.id.textWeb);
        floatContainer = findViewById(R.id.floatContainer);
        scrollView = findViewById(R.id.scrollView);
        tabContainer = findViewById(R.id.tabContainer);
        soundTv = findViewById(R.id.soundTv);
        textTv = findViewById(R.id.textTv);
        soundLine = findViewById(R.id.soundLine);
        textLine = findViewById(R.id.textLine);
        componentLinear = findViewById(R.id.linear_layout_relative_component);
        albumLogoTag = Utility.findViewById(mRootView, R.id.albumLogoTag);
        programView = Utility.findViewById(mRootView, R.id.programView);
        timingTv = Utility.findViewById(mRootView, R.id.timing);
        summaryOpen = Utility.findViewById(mRootView, R.id.arrowIco);
        showMoreDes = Utility.findViewById(mRootView, R.id.showMoreDes);
        tvPlayCount = Utility.findViewById(mRootView, R.id.tvPlayCount);
        tvAuthor = Utility.findViewById(mRootView, R.id.tvAuthor);
        tvPublishData = Utility.findViewById(mRootView, R.id.tvPublishData);
        titleView = Utility.findViewById(mRootView, R.id.titleView);
        logoView = Utility.findViewById(mRootView, R.id.image_toggle_bg);
        seekbar = Utility.findViewById(mRootView, R.id.seekbar);
        speedIv = Utility.findViewById(mRootView, R.id.speedIv);
        tvProgress = Utility.findViewById(mRootView, R.id.tvProgress);
        tvMax = Utility.findViewById(mRootView, R.id.tvMax);
        iv_more = Utility.findViewById(mRootView, R.id.iv_more);
        logoContainer = Utility.findViewById(mRootView, R.id.logoContainer);
        togglePauseBtn = Utility.findViewById(mRootView, R.id.togglePauseBtn);
        streamLineBtn = Utility.findViewById(mRootView, R.id.streamLineBtn);
        audioDesTitle = Utility.findViewById(mRootView, R.id.audioDesTitle);
        text_editor = Utility.findViewById(mRootView, R.id.text_editor);
        text_source = Utility.findViewById(mRootView, R.id.text_source);
        webBrowser = Utility.findViewById(mRootView, R.id.webBrowser);
        tvLayout = Utility.findViewById(mRootView, R.id.layout_audio_detail_content);
        tvLayout.setExpandTypeface(null, Typeface.BOLD);
        // rl_webBrowser = Utility.findViewById(mRootView, R.id.rl_webBrowser);
        //webMaxHeight = getResources().getDimensionPixelSize(R.dimen.dimen100);
        //tv_webmore = Utility.findViewById(mRootView, R.id.tv_webmore);
        spiderView = Utility.findViewById(mRootView, R.id.spiderView);
        //tv_summary = Utility.findViewById(mRootView, R.id.tv_summary);
        audioDes = Utility.findViewById(mRootView, R.id.audioDes);
        summaryLayout = Utility.findViewById(mRootView, R.id.cl_product);
        togglePauseBtn.setOnClickListener(this);
        findViewById(R.id.backIv).setOnClickListener(this);
        timingTv.setOnClickListener(this);

        if (streamLineBtn != null) {
            streamLineBtn.setOnClickListener(this);
        }
        if (iv_more != null) {
            LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(this).getNewsDetailConfig().getLinkedHashSet();
            if (!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON)) {
                iv_more.setVisibility(View.GONE);
            } else {
                iv_more.setVisibility(View.VISIBLE);
            }
            iv_more.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClickUtils.delayClickable(v);
                    if (shareWrapTopRight == null) {
                        shareWrapTopRight = new ShareWrap(BaseAudioActivityHalfCCTV7.this, false);
                    }
                    shareWrapTopRight.setShowFunction(true);
                    shareWrapTopRight.init(articleItem, new CatalogItem());
                    shareWrapTopRight.show(mRootView);
                }
            });
        }

        /**
         * 新的评论弹出方式
         * */
        text_comment_audio.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 修改为弹窗样式
                if (articleItem!=null){
                    XCommentDialogFragment fragment =new XCommentDialogFragment();
                    Bundle bundle =new Bundle();

                    bundle.putParcelable("data", articleItem);
                    bundle.putBoolean("HIDE_COMMENT_ICO", true);
                    bundle.putInt("type", 1);
                    fragment.setArguments(bundle);
                    fragment.show(getSupportFragmentManager(), "bottom");

                }

            }
        });

        text_like_audio.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SupportKit.INSTANCE.support(BaseAudioActivityHalfCCTV7.this, SupportKit.TYPE_1, articleItem.getId(), new SupportKit.ISupportResult() {
                    @Override
                    public void onSupportResult(boolean result, boolean isSupport) {
                        if (isSupport) {
                            text_like_audio.setCompoundDrawablesWithIntrinsicBounds(
                                    0,
                                    R.drawable.icon_liked_audio,
                                    0,
                                    0
                            );
                            CDPTrackReportManager.getInstance().RadioSubjectLike(articleItem);
                        } else {
                            text_like_audio.setCompoundDrawablesWithIntrinsicBounds(
                                    0,
                                    R.drawable.icon_like_audio,
                                    0,
                                    0
                            );
                        }
                    }
                }, false, articleItem);
            }
        });

        text_share_audio.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ClickUtils.delayClickable(v);
                if (shareWrapTopRight == null) {
                    shareWrapTopRight = new ShareWrap(BaseAudioActivityHalfCCTV7.this, false);
                }
                shareWrapTopRight.setShowFunction(true);
                shareWrapTopRight.init(articleItem, new CatalogItem());
                shareWrapTopRight.show(mRootView);
            }
        });

        text_collect_audio.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                text_collect_audio.setEnabled(false);
                collectionController.collection();
            }
        });


        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Log.e("AAXXCASASA", "" + scrollY);
                if (!isSoundMod) return;
                if (scrollX > hideHeight) {
                    if (floatContainer.getVisibility() != View.GONE) {
                        floatContainer.setVisibility(View.GONE);
                    }
                } else {
                    if (floatContainer.getVisibility() != View.VISIBLE) {
                        floatContainer.setVisibility(View.VISIBLE);
                    }
                    floatContainer.setAlpha((hideHeight - scrollY) * 1f / hideHeight);
                }
            }
        });
        /*RxUtils.rxClick(tv_webmore, new RxUtils.OnClickInterf() {
            @Override
            public void onViewClick(View view) {
                tv_webmore.setSelected(!tv_webmore.isSelected());
                setWebMore();

                ViewGroup.LayoutParams params = webBrowser.getLayoutParams();
                if (!tv_webmore.isSelected() && webBrowser.getHeight() > webMaxHeight) {
                    params.height = webMaxHeight;
                } else {
                    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
                webBrowser.setLayoutParams(params);
            }
        });*/
        dealStatusBar();
    }

    @Override
    public void onBackPressed() {
        if (shareWrapTopRight != null && shareWrapTopRight.isShowing()) {
            shareWrapTopRight.dismiss();
            return;
        }
        super.onBackPressed();
    }

    private void dealStatusBar() {
        ViewGroup.LayoutParams params = floatContainer.getLayoutParams();
        if (params instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) params;
            marginLayoutParams.topMargin = Math.max(marginLayoutParams.topMargin, StatusBarUtil.getStatusBarHeight(this));
            floatContainer.setLayoutParams(params);
        }
    }

    @Override
    public int getStatusBarColor() {
        return Color.TRANSPARENT;
    }

    @Override
    protected boolean getFitSystemWindow() {
        return false;
    }

    protected void getArgs() {
        Uri uriData = getIntent().getData();
        if (uriData != null) {
            isFromH5OpenToReStart = UriTool.INSTANCE.isFromH5OpenToReStart(this, uriData);
            String articleid = uriData.getQueryParameter("articleid");
            String title = uriData.getQueryParameter("title");
            String cname = uriData.getQueryParameter("cname");
            String tag = uriData.getQueryParameter("tag");
            catalogItem = new CatalogItem();
            catalogItem.setCatname(cname);
            articleItem = new ArticleItem();
            try {
                articleItem.setTitle(title);
                if (!TextUtils.isEmpty(articleid))
                    articleItem.setId(Long.valueOf(articleid));
            } catch (Exception e) {
            }
        } else {
            articleItem = getIntent().getParcelableExtra("data");
            catalogItem = getIntent().getParcelableExtra("catalog");
            bgColor = getIntent().getIntExtra("bgColor", -1);
        }
        try {
            if (catalogItem == null)
                catalogItem = new CatalogItem();
            catalogItem.setCatalog_type(getIntent().getStringExtra("category"));
            catalogItem.setCatid(getIntent().getStringExtra("navigate_id"));
            if (articleItem == null) {
                articleItem = new ArticleItem();
                articleItem.setId(Long.parseLong(getIntent().getStringExtra("article_id")));
                articleItem.setSummary(getIntent().getStringExtra("summary"));
                articleItem.setTitle(getIntent().getStringExtra("title"));
                articleItem.setUrl(getIntent().getStringExtra("url"));
                articleItem.setIsAdvertisement(getIntent().getIntExtra("isAdvertisement", 0));
                articleItem.setIsBarrage(getIntent().getIntExtra("isBarrage", 0));
                articleItem.setReferSourceID(getIntent().getStringExtra("ReferSourceID"));
                articleItem.setIsComment(getIntent().getStringExtra("isComment"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    /*public void setWebMore() {

        if (tv_webmore.isSelected()) {
            tv_webmore.setText("收起");
        } else {
            tv_webmore.setText("展开全部");

        }


    }*/

//    /**
//     * 获取组件的相关数据
//     */
//    protected void getComponentData() {
//
//        if (componentLinear != null) {
//            topicListDataInvoker = new TopicListDataInvoker(new DataInvokeCallBack<TopicDetailDataReciver>() {
//                @Override
//                public void success(TopicDetailDataReciver data) {
//                    Log.w(TAG, "success");
//                    componentLinear.removeAllViews();
//                    NewsDetailComponentUtils.addComponentList(componentLinear, data.componentItems, articleItem, BaseAudioActivityHalfCCTV7.this, getSupportFragmentManager(), 1);
//
//                }
//
//                @Override
//                public void fault(Object data) {
//                    Log.e(TAG, "fault");
//                }
//            });
//            if (articleItem.getCid() > 0) {
//                topicListDataInvoker.getTopicDetailById(String.valueOf(articleItem.getCid()), pageNum, pageSize);
//            } else {
//                topicListDataInvoker.getArticleById(String.valueOf(articleItem.getId()), UserInfo.getUserInfo(this).getUserid(), articleItem.getParentId(), pageNum, pageSize);
//            }
//        }
//    }


    /**
     * 进入登录
     *
     * @param context
     */
    protected void intoLogin(Context context) {
        //      ToastUtil.show(context, R.string.please_login);
        LoginUtils.request_source = "音频详情";
        LoginUtils.invokeLogin(context);
    }

    @Override
    public int getLayoutResID() {
        return R.layout.activity_audio_player_half_cctv7;
    }

    private Long launchTimeLong = 0L;
    public long startPosition = 0L;
    public long stopPosition = 0L;
    public boolean isCompleted = false;

    public void onClick(View v) {
        if (v.getId() == R.id.togglePauseBtn) {
            KillMusicUtils.hideReadNewsWin();
            checkToPlay();
        } else if (v.getId() == R.id.streamLineBtn) {
            showStreamLine();
        } else if (v.getId() == R.id.timing) {
            showTiming();
            TXReportManager.getInstance().app_jhapp_content_detail_interact("点击定时关闭", null, null, articleItem);

        } else if (v.getId() == R.id.backIv) {
            finish();
            //overridePendingTransition(0, R.anim.slide_out_bottom3);
        } else if (v.getId() == R.id.programView) {
            TXReportManager.getInstance().app_jhapp_content_detail_interact("点击列表", null, null, articleItem);
            onProgramViewClick();
        }
    }

    @Override
    public void finish() {
        ReportKit.INSTANCE.escalationArticleTime();
        super.finish();
    }

    public void onToggleClick() {

    }

    public void onProgramViewClick() {

    }

    abstract void showStreamLine();


    protected Drawable tintDrawable(int drawableId, @ColorInt int color) {
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), drawableId);
        Drawable bitmapDrawable = new BitmapDrawable(getResources(), bmp);
        bitmapDrawable = Utility.tintDrawable(color, bitmapDrawable.mutate());
        return bitmapDrawable;
    }

    protected int getPaletteColor() {
        return Color.RED;
    }

    //开启语音播报
    private void startReadNews() {
        if (TextUtils.isEmpty(apsKit.getUrl())) {
            return;
        }
        TXReportManager.getInstance().voice_read(articleItem);
        articleItem.setText_audio_url(apsKit.getUrl());
        AudioFloatManager.Companion.getInstance(this).setAudioAlbumArticleId(null);
        if (apsKit.isTaskPlaying()) {
            AudioFloatManager.Companion.getInstance(this).setArticle(articleItem);
            AudioFloatManager.Companion.getInstance(this).setCatalogItem(catalogItem);
        }
        if (audioType == 2 || AudioAlbumArticleId != null) {
            if (floatTop == 0) {
                floatTop =
                        Utility.getScreenHeight(this) - getResources().getDimensionPixelSize(R.dimen.dimen71) - StatusBarUtil.getStatusBarHeight(this);
                if (ImmersionBar.hasNavigationBar(this)) {
                    floatTop -= ImmersionBar.getNavigationBarHeight(this);
                }
            }

            AudioFloatManager.Companion.getInstance(this).setOpenArticleId(articleItem.getId());
            AudioFloatManager.Companion.getInstance(this).setAudioAlbumArticleId(AudioAlbumArticleId);
            MusicEntity musicEntity = apsKit.getCurrentMusic();
            if (musicEntity != null) {
                AudioFloatManager.Companion.getInstance(this).show(floatTop, musicEntity.getMusicTitle());
            } else {
                AudioFloatManager.Companion.getInstance(this).show(floatTop);
            }
        } else {
            AudioFloatManager.Companion.getInstance(this).show();
        }
    }

    protected final void sendShowFloaWinMsg() {
        if (!apsKit.intentPlaying() && !apsKit.isPlaying()) {
            realFinish();
            return;
        }
        if (PermissionUtils.checkPermission(this)) {
            startReadNews();
            realFinish();
        } else {
            AudioFloatManager.showPermissionAsk(this, new OnPermissionResult() {
                @Override
                public void permissionResult(boolean isOpen) {
                    if (isOpen) {
                        startReadNews();
                    }
                    realFinish();
                }
            });
        }

    }

    /**
     * 这里真实的去finish() 用于
     * 处理退出当前也没的时候，需要申请悬浮窗权限的时候，不能真实的调用finish()否则取不到权限申请的结果
     */
    public void realFinish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (readStatusInvoker != null) {
            readStatusInvoker.destory();
            readStatusInvoker = null;
        }
//        if (commentDialogFram != null) {
//            commentDialogFram.dismiss();
//            commentDialogFram.destory();
//        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

    }


    /**
     * 走添加阅读数接口
     */
    private void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        if (audioType != 2) {
            readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
        }
    }


    int lastType = -1;

    /**
     * 检查网络状态
     */
    @Override
    public void checkNetType() {
        PermissionUtil.INSTANCE.invokeNetWorkPermission(this, new IPermissionsAgree() {
            @Override
            public void onAgree() {
                extracted();

            }

            @Override
            public void onRefuse() {

            }

            @Override
            public void hasPermissions() {
                extracted();

            }
        });
    }

    private void extracted() {
        ConnectivityManager cm = SystemServiceManager.getConnectivityManager(getApplicationContext());
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        //有網絡
        if (networkInfo != null && networkInfo.isAvailable()) {
            hasNetWork = true;
            //目前變成手機流量狀態
            if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                if (networkInfo.getType() != lastType) {
                    if (MMKV.defaultMMKV().getBoolean(XKey.VIDEO_TIP_KEY, true)) {
                        netChangeStopPlay();
                        showNoticeDialoge(TYPE_NOT_WIFI);
                    }
                }
                //目前變成手機WiFi狀態
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                netChangePlay();
            }
            lastType = networkInfo.getType();
        } else {
            //沒網絡的時候
            hasNetWork = false;
            netChangeStopPlay();
            noNetwork();
            showNoticeDialoge(TYPE_NO_NETWORK);
        }
    }

    public void check() {

        ConnectivityManager cm = SystemServiceManager.getConnectivityManager(getApplicationContext());
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        //有網絡
        if (networkInfo != null && networkInfo.isAvailable() && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            if (MMKV.defaultMMKV().getBoolean(XKey.VIDEO_TIP_KEY, true)) {
                netChangeStopPlay();
            }
        }
    }


    public void checkToPlay() {
        ConnectivityManager cm = SystemServiceManager.getConnectivityManager(getApplicationContext());
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (apsKit.isPlaying()) {
            apsKit.toggle();
            return;
        }
        onToggleClick();
        if (networkInfo != null && networkInfo.isAvailable()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                if (MMKV.defaultMMKV().getBoolean(XKey.VIDEO_TIP_KEY, true)) {
                    togglePauseBtn.setChecked(false);
                    netChangeStopPlay();
                    showNoticeDialoge(TYPE_NOT_WIFI);
                } else {
                    netChangePlay();
                }
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                netChangePlay();
            }
        } else {
            showNoticeDialoge(TYPE_NO_NETWORK);
        }
    }

    /**
     * 子类重写
     */
    public void netChangeStopPlay() {
        if (apsKit.isPlaying()) {
            apsKit.toggle();
        }
    }

    /**
     * 子类重写
     */
    public void netChangePlay() {
        if (apsKit != null && !apsKit.isPlaying()) {
            apsKit.toggle();
        }
    }


    void showNoticeDialoge(int noticType) {

        if (dialog != null && dialogType == noticType && dialog.isShowing()) {
            return;
        }
        dialogType = noticType;
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.audio_notic, null);
        TextView title = contentView.findViewById(R.id.audio_notice_title);
        TextView btn1 = contentView.findViewById(R.id.audio_notice_btn1);
        TextView btn2 = contentView.findViewById(R.id.audio_notice_btn2);
        dialog = null;
        dialog = new Dialog(this, R.style.loadingDialogStyle);

        dialog.setContentView(contentView);
        // 无网络提示
        if (noticType == TYPE_NO_NETWORK) {
            title.setText(R.string.audio_notice_noNetWork);
            btn1.setText(R.string.audio_notice_Got_it);
            btn2.setText(R.string.audio_notice_Go_check);
            btn1.setOnClickListener(v -> {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
            btn2.setOnClickListener(v -> {

                Intent intent = null;
                intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                startActivity(intent);
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
            // Wifi变流量
        } else if (noticType == TYPE_NOT_WIFI) {//点击继续以后不再提示，点击关闭下次继续提示
            title.setText(R.string.audio_notice_isNotWifi);
            btn1.setText(R.string.audio_notice_goON);
            btn2.setText(R.string.audio_notice_close);
            btn1.setOnClickListener(v -> {
                MMKV.defaultMMKV().putBoolean(XKey.VIDEO_TIP_KEY, false);
                netChangePlay();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
            btn2.setOnClickListener(v -> {
                apsKit.pause();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });

            if (isFinish) return;
            dialog.show();
        }
        if (isFinish) return;
        dialog.show();
    }

    public void setCl_lyaoutVisiable(int show) {
        if (summaryLayout != null) {

            summaryLayout.setVisibility(show);
        }
    }

    abstract protected void onPaidAudio(String audio);


    /**
     * 获取其余支付后需要显示的View
     */
    protected List<View> getPaidViews() {
        return null;
    }


    public void isChartRoom(Context context, String id, ChatRoomListener listener) {
        NewsDetailInvoker newsDetailInvoker = new NewsDetailInvoker(new DataInvokeCallBack<ArticleItemReciver>() {
            @Override
            public void success(ArticleItemReciver data) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }

                if (data != null) {
                    if (data.chatRoom != null && data.chatRoom.isOpen) {
                        String author = "";
                        if (data.articleItem != null && data.articleItem.Author != null) {
                            author = data.articleItem.Author;
                        }
                        listener.chartRoom(true, author);
                    } else {
                        listener.chartRoom(false, null);
                    }
                } else {
                    listener.chartRoom(false, null);
                }
            }

            @Override
            public void fault(Object data) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                listener.chartRoom(false, null);
            }
        });

        newsDetailInvoker.getArticleById("" + id, "");
    }

    public interface ChatRoomListener {
        void chartRoom(boolean chart, String author);
    }

    /**
     * 定时
     */
    private void showTiming() {
        if (timingAdapter != null) {
            timingList.clear();
            timingList.add("不开启");
            if (audioType != 1) {
                int max = seekbar.getMax();
                int progress = seekbar.getProgress();
                progress = max - progress;
                int min = progress / 60;
                int sec = progress % 60;
                timingList.add("播完当前(倒计时" + (min > 9 ? min : "0" + min) + ":" + (sec > 9 ? sec : "0" + sec) + ")");
            }
//            if (audioType == 2) {
//                timingList.add("播完两集");
//            }
            timingList.add("10分钟");
            timingList.add("30分钟");
            timingList.add("60分钟");
            timingList.add("自定义");
            timingAdapter.setListData(timingList);
            timingAdapter.notifyDataSetChanged();

            for (int i = 0; i < timingList.size(); i++) {
                if (timingList.get(i).equals(timeOffInfo)) {
                    timeOffIndex = i;
                    break;
                }
            }
        }

        if (audioBottomPopWin.isShowing()) {
            return;
        }
        audioBottomPopWin.setListAdaptor(timingAdapter);
        audioBottomPopWin.setPopTitle("定时关闭");
        audioBottomPopWin.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
        audioBottomPopWin.setItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (timeOffIndex != position || timingList.get(position).equals("自定义")) {
                    timeOffIndex = position;
                    if (timerTask != null) {
                        timerTask.cancel();
                    }
                    String title = timingList.get(position);
                    if (title.equals("不开启")) {
                        if (apsKit != null) {
                            checkCurrent = false;
                            apsKit.timeOffClear();
                        }
                        timingTv.setText("定时");
                    } else if (title.indexOf("播完当前") >= 0) {
                        if (apsKit != null) {
                            checkCurrent = true;
                            apsKit.timeOffBySize(1, title);
                        }
//                        timingTv.setText("播完当前");
                    } else if (title.equals("播完两集")) {
                        if (apsKit != null) {
                            checkCurrent = false;
                            apsKit.timeOffBySize(2, title);
                        }
                        timingTv.setText("播完两集");
                    } else if (title.equals("10分钟")) {
                        if (apsKit != null) {
                            checkCurrent = false;
                            apsKit.timedOffBySecond(10 * 60, title);
                        }

                    } else if (title.equals("30分钟")) {
                        if (apsKit != null) {
                            checkCurrent = false;
                            apsKit.timedOffBySecond(30 * 60, title);
                        }

                    } else if (title.equals("60分钟")) {
                        if (apsKit != null) {
                            checkCurrent = false;
                            apsKit.timedOffBySecond(60 * 60, title);
                        }
                    } else if (title.equals("自定义")) {
                        checkCurrent = false;
                        audioBottomPopWin.dismiss();
                        showCustomTimeOffWin();
                    }

                }
            }
        });
        backgroundAlpha(0.3f);
        audioBottomPopWin.setOnDismissListener(() -> {
            backgroundAlpha(1f);
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }


    public void showCustomTimeOffWin() {
        if (customTimeOffSelector == null) {
            customTimeOffSelector = new TimePickerBottomDialog(this, R.style.MBottomSheetDialog, new Function1<Long, Unit>() {
                @Override
                public Unit invoke(Long aLong) {
                    if (apsKit != null) {
                        apsKit.timedOffBySecond((int) (aLong / 1000), "自定义");
                    }

                    return null;
                }
            });
        }
        customTimeOffSelector.showDialog();

    }

    boolean settedLogo = false;
    protected String mImgUrl;

    protected void setLogo(String imgUrl) {
        //if (settedLogo) return;
        if (TextUtils.isEmpty(imgUrl)) {
            Drawable drawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.cctv7_loading_img);
            logoView.setImageDrawable(drawable);
            setLogoContainer(drawable);
            return;
        }
        if (imgUrl.equals(mImgUrl)) {
            return;
        }
        mImgUrl = imgUrl;
//        if (TextUtils.isEmpty(articleItem.getLogo())) return;
        //  if (TextUtils.isEmpty(articleItem.getAppCustomParams())) return;
        //settedLogo = true;
        /*if (bgColor != -1) {
            logoContainer.setBackgroundColor(bgColor);
        }*/
        /*JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(articleItem.getAppCustomParams());
            JSONObject customStyle = jsonObject.optJSONObject("customStyle");

            JSONArray imgPath = customStyle.optJSONArray("imgPath");
            if (!TextUtils.isEmpty(articleItem.getProp1())) {
                imgUrl = articleItem.getProp1();
            } else {
                imgUrl = (String) imgPath.get(0);
            }
        } catch (JSONException e) {
            e.printStackTrace();

        }*/

        //推送过来没有logo
        ImageKitKt.loadX(this, ImageKitKt.buildUrl(2, imgUrl), 0, new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                mImgUrl = null;
                Drawable drawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.cctv7_loading_img);
                logoView.setImageDrawable(drawable);
                setLogoContainer(drawable);
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                if (isFinishing() || isDestroyed()) {
                    return false;
                }
                logoView.setImageDrawable(resource);
                setLogoContainer(resource);
                return false;
            }
        });
    }

    private void setLogoContainer(Drawable resource) {
        //if (bgColor != -1) return ;
        Bitmap bitmap = DrawableKt.toBitmap(resource, resource.getIntrinsicWidth(), resource.getIntrinsicHeight(), null);
        Palette.from(bitmap).maximumColorCount(16)
                .generate(new Palette.PaletteAsyncListener() {
                    @Override
                    public void onGenerated(@Nullable Palette palette) {
                        if (palette != null) {
                            Palette.Swatch swatch = palette.getDominantSwatch();//最多的一种
                            Palette.Swatch s1 = palette.getVibrantSwatch();
                            Palette.Swatch s2 = palette.getMutedSwatch();
                            Palette.Swatch s3 = palette.getLightMutedSwatch();
                            Palette.Swatch s4 = palette.getDominantSwatch();
                            if (swatch != null) {
                                logoContainer.setBackgroundColor(swatch.getRgb());
                            } else if (s1 != null) {
                                logoContainer.setBackgroundColor(s1.getRgb());
                            } else if (s2 != null) {
                                logoContainer.setBackgroundColor(s2.getRgb());
                            } else if (s3 != null) {
                                logoContainer.setBackgroundColor(s3.getRgb());
                            } else if (s4 != null) {
                                logoContainer.setBackgroundColor(s4.getRgb());
                            }
                        }
                    }
                });
    }

    class TimingAdaptor extends BaseAdaptor<String> {
        int selectedColor = Color.parseColor("#D43D3D");
        int defaultColor = Color.parseColor("#222222");

        public TimingAdaptor(Context context, List<String> list) {
            super(context, list);
        }

        public TimingAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_bottom_pop_item, null);
            }
            TextView title = Utility.findViewById(convertView, R.id.title);
            title.setText(getItem(position));

            if (position == timeOffIndex) {
                title.setTextColor(selectedColor);
            } else {
                title.setTextColor(defaultColor);
            }

            return convertView;
        }

    }
}